package com.xgq.drink.config;

import com.xgq.drink.websocket.WebSocketAuthenticationHandler;
import com.xgq.drink.websocket.WebSocketChatHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * WebSocket配置类
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    private static final Logger log = LoggerFactory.getLogger(WebSocketConfig.class);

    @Autowired
    private WebSocketAuthenticationHandler webSocketAuthenticationHandler;

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        log.info("配置WebSocket消息代理");
        // 用户订阅的目的地前缀
        registry.enableSimpleBroker("/topic", "/queue", "/user");
        // 发送消息的目的地前缀
        // 添加应用目的前缀
        registry.setApplicationDestinationPrefixes("/app");
        // 添加用户级点对点前缀
        registry.setUserDestinationPrefix("/user");
        log.info("WebSocket消息代理配置完成");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        log.info("注册WebSocket端点");
        
        // 配置客户端使用SockJS连接的端点
        registry.addEndpoint("/wsSockjs")
                .setAllowedOriginPatterns("*") // 允许所有跨域
                .addInterceptors(webSocketAuthenticationHandler)
                .withSockJS(); // 启用SockJS作为备选方案
        log.info("SockJS端点 /ws-sockjs 注册完成");

        // 配置客户端使用原生WebSocket连接的端点
        registry.addEndpoint("/ws")
                .setAllowedOriginPatterns("*")
                .addInterceptors(webSocketAuthenticationHandler);
        log.info("原生WebSocket端点 /ws 注册完成");
    }
} 